package org.wu.reggie.filter;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.AntPathMatcher;
import org.wu.reggie.common.R;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 实现过滤器需要实现Filter接口
 */
@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {


    @Autowired
    private StringRedisTemplate redisTemplate;


    // 该类的作用主要用于匹配url地址
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        // 向下转型 使用HttpServletRequest和HttpServletResponse的特有方法
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 1 获取本次请求uri http://localhost:8080/backend/index.html
        String requestURI = request.getRequestURI();

        // 2 定义一个可以直接放行资源地址的数组
        String[] urls = {
                "/employee/login",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };

        // 3 判断本次请求的uri
        boolean flag = checkUri(urls, requestURI);
        if (flag) {
            // 本次请求的路径是属于不需要拦截的地址，可以直接放行
            filterChain.doFilter(request, response);
            return;
        }

        // 4 检查是否登录了 如果已经登录可以直接放行
        Object employee = request.getSession().getAttribute("employee");
        if (employee != null) {
            // 用户已经登录
            filterChain.doFilter(request, response);
            return;
        }

        // 检查前台是否登录
//        String user = redisTemplate.opsForValue().get("user");
        Object user = request.getSession().getAttribute("user");
        if (user != null) {
            filterChain.doFilter(request, response);
            return;
        }

        // 由于这里不是controller 所以返回对象的时候需要自己转换为json并写出
        String resultJson = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(resultJson);

        // 5 如果没有登录返回错误信息 回到登录页面

    }


    /**
     * 检查本次的请求是否符合放行的
     *
     * @param urls       放行的资源路径
     * @param requestURI 请求地址
     * @return
     */
    private boolean checkUri(String[] urls, String requestURI) {
        for (String url : urls) {
            if (antPathMatcher.match(url, requestURI)) {
                return true;
            }
        }
        return false;
    }


}
